<template>
  <div class="login-container">
    <el-form
        :model="form"
        :rules="rules"
        ref="loginForm"
        label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
            v-model="form.username"
            placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
            v-model="form.password"
            placeholder="请输入密码"
            type="password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            @click="submitForm('loginForm')"
        >登录
        </el-button>
        <el-button
            @click="resetForm('loginForm')"
        >重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import http from '@/http.js'; // 导入封装好的axios实例

import { setLocalStorageWithExpire, getLocalStorageWithExpire,removeItem } from '@/localStorageUtil.js';
export default {
  data() {
    return {
      form: {
        username: '123',
        password: '123123'
      },
      rules: {
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {min: 6, message: '密码长度至少为6位', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          http.post('/admin/login', this.form) // 这里的/api/some-endpoint是相对baseURL的具体接口路径
              .then(response => {
                console.log(response); // 处理成功获取到的数据
                // 模拟登录成功，设置登录状态到本地存储，实际需与后端交互验证
                setLocalStorageWithExpire('isLoggedIn', 'true',30)
                this.$router.push('/'); // 登录成功后跳转到首页
              })
              .catch(error => {
                console.log(error); // 处理请求失败的情况
              });
        } else {
          console.log('表单验证失败，请检查输入信息');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style scoped>
.login-container {
  width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}
</style>